package com.newsappserver.userservice.controller;

import com.newsappserver.userservice.dto.request.AuthRequest;
import com.newsappserver.userservice.dto.request.IntrospectRequest;
import com.newsappserver.userservice.dto.response.ApiResponse;
import com.newsappserver.userservice.dto.response.AuthResponse;
import com.newsappserver.userservice.dto.response.IntrospectResponse;
import com.newsappserver.userservice.service.AuthService;
import com.nimbusds.jose.JOSEException;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;

@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    AuthService authService;

    // 登录
    // httpie 测试: http POST :8080/api/auth/login username=root  password=12345678
    // 管理员登录: http POST :8080/api/auth/login username=admin  password=admin
    @PostMapping({"/login", "signin"})
    ApiResponse<AuthResponse> authenticate(@RequestBody AuthRequest authRequest) {
        var result = authService.authenticate(authRequest);
        return ApiResponse.<AuthResponse>builder()
                .code(HttpStatus.OK.value())
                .message(result.isAuthenticated() ? "Authenticated" : "Not authenticated")
                .data(result)
                .build();
    }

    // 查看
    /*
    POST http://localhost:8080/api/auth/introspect
    Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJpc3MiOiIxNjkwNTQ0NTUwQHFxLmNvbSIsInN1YiI6ImFkbWluIiwiZXhwIjoxNzQ4ODU3MzM3LCJpYXQiOjE3NDYyNjUzMzcsInNjb3BlIjoiIn0.yfccgmnrVqKRfEFF0hUmoGiHcJQemPmWUtKHFlP6xQmn-oD028328sqU8Wmk157YOdK6wqgj55Qm4xD4ha38sw
    Content-Type: application/json

    {
        "authenticated": true,
        "token": "eyJhbGciOiJIUzUxMiJ9.eyJpc3MiOiIxNjkwNTQ0NTUwQHFxLmNvbSIsInN1YiI6ImFkbWluIiwiZXhwIjoxNzQ4ODU3MzM3LCJpYXQiOjE3NDYyNjUzMzcsInNjb3BlIjoiIn0.yfccgmnrVqKRfEFF0hUmoGiHcJQemPmWUtKHFlP6xQmn-oD028328sqU8Wmk157YOdK6wqgj55Qm4xD4ha38sw"
    }
     */
    @PostMapping("/introspect")
    ApiResponse<IntrospectResponse> introspect(@RequestBody IntrospectRequest introspectRequest)
            throws ParseException, JOSEException {
        var result = authService.introspect(introspectRequest);

        return ApiResponse.<IntrospectResponse>builder()
                .code(HttpStatus.OK.value())
                .message(result.isValid() ? "Validated" : "Not validated")
                .data(result)
                .build();
    }
}
